import { reactive, onMounted } from 'vue';
import _ from 'lodash';
import Bus from '@/utils/bus';
import { useRoute } from "vue-router";
import * as Store from '@/store';
import useLeft from './useLeft';
import * as Api from '@/api/filmRead/filmRead';
import type * as ApiType from '@/api/filmRead/filmRead.d';

const rightHooksData = reactive({
  findingVisible: false,
  findingValue: "",
  diagnosisVisible: false,
  diagnosisValue: "",
  rejectFilmVisible: false,
  rejectFilmValue: "",
  yayVisible: false,
  yayValue: undefined as unknown as number,
  form: {} as {[x: string | number]: any},
  formOptions: [] as Right.FormOptions[]
})

const useRight = () => {
  const FilmRead = Store.useFilmRead();
  const route = useRoute();
  const interfaceData = FilmRead.interfaceData
  const dictionaryData = FilmRead.dictionaryData
  const LeftHooks = useLeft();
  const handleLesionClick = (item: any) => {
    if(item.type === 'lesion' || item.id === ''){
      seriesChangeActive((item as unknown as any).id)
    }
  }
  Bus.on("lesionClick", handleLesionClick);

  /**
   * 序列征象、标注征象的表单变更事件
   * @param value 当前征象改变的值
   */
  const handleChange = (value: any, item: Right.FormOptions) => {
    // 处理无的互斥
    if (item.type === "checkbox") {
      if (Array.isArray(value)) {
        if (value.includes('-1') && value.length == 2 && value[0] === '-1') {
          rightHooksData.form[item.field] = (value as any[]).filter((it: any) => it !== "-1") as { [x: string | number]: any };
          value = rightHooksData.form[item.field] as any[];
        }
        if (value.includes('-1')) {
          rightHooksData.form[item.field] = value.filter((it:any) => it === "-1") as { [x: string | number]: any };
          value = rightHooksData.form[item.field] as any[];
        }
      }
    }
    rightHooksData.form[item.field] = value//?
    // 保存征象
    const params: ApiType.SaveCrParams = {
      arId: FilmRead.interfaceData?.seriesList[FilmRead.currentThumbnailIndex].id,//标注列表id
      acrList: [] as ApiType.CrItem[]//结果列表，支持多个
    }
    if (LeftHooks.leftHooksData.currentIndex === "") {
      // 大征象(序列征象)保存--alrId 不传为大征象
    } else {
      // 小征象(标注征象)保存
      params.alrId = +LeftHooks.leftHooksData.currentIndex//病灶id
    }
    params.acrList.push(_.cloneDeep({
      componentId: item.componentId,
      result: getStringResult(value, item.type)
    }))
    saveSeriesComp(params, item);
  }

  /**
   * 将数组格式的表单变更成字符串形式方法
   * @param result 当前需要变更的result
   * @param type 当前变更的类型
   * @returns 返回字符串result
   */
  const getStringResult = (result: string | string[], type: string) => {
    if (Array.isArray(result)) {
      if (type === "checkbox") {
        return result.join(",");
      }
      if (type === "child_select") {
        return result.join("@#@");
      }
      return result.join('');
    } else {
      return result;
    }
  }

  /**
   * 创建征象信息请求的接口方法
   * @param params 创建征象调用接口请求的参数集合
   */
  /*const createSeriesComp = async (params: ApiType.AddCrParams, itemOption: Right.FormOptions) => {
    const res = await Api.saveCrListData(params)
    // 更新字典result
    const { acrList, alrId } = res.data;
    if (LeftHooks.leftHooksData.currentIndex === "") {
      // 序列征象字典数据新增
      if (dictionaryData.seriesDataList) {
        let temp = dictionaryData.seriesDataList[FilmRead.interfaceData?.seriesList[FilmRead.currentThumbnailIndex].seriesUid];
        temp && (temp = temp.map(item => {
          if (item.componentId === acrList[0].componentId) {
            item.result = acrList[0].result;
            item.id = acrList[0].acrId;
            itemOption.result = acrList[0].result;
            itemOption.id = acrList[0].acrId;
          }
          return item;
        }))
      }
    } else {
      // 标注征象字典数据新增
      if (dictionaryData.imageSeriesDataList) {
        let temp = dictionaryData.imageSeriesDataList[LeftHooks.leftHooksData.currentIndex];
        temp && (temp = temp.map(item => {
          if (item.componentId === acrList[0].componentId) {
            item.result = acrList[0].result;
            item.id = acrList[0].acrId;
            itemOption.result = acrList[0].result;
            itemOption.id = acrList[0].acrId;
          }
          return item;
        }))
      }
    }
  }*/

  /**
   * 新增、编辑征象信息请求的接口方法
   * @param params 编辑征象调用接口请求的参数集合
   */
  const saveSeriesComp = async (params: ApiType.SaveCrParams, itemOption: Right.FormOptions) => {
    const res:any = await Api.saveCrListData(params)
    const acrList = res.data?.acrList || []
    // 更新字典result
    if (LeftHooks.leftHooksData.currentIndex === "") {
      // 序列征象字典数据变更
      if (dictionaryData.seriesDataList) {
        let temp = dictionaryData.seriesDataList[FilmRead.interfaceData?.seriesList[FilmRead.currentThumbnailIndex].seriesUid];
        temp && params.acrList.map(item => {
          const compItem = temp.find((it) => (it.id === itemOption.id) && (it.name === itemOption.name))
          if (compItem) {
            compItem.result = rightHooksData.form[compItem.code];
            itemOption.result = rightHooksData.form[compItem.code];
            const current = acrList.find(it => it.componentId === item.componentId)
            compItem.id = current && current.acrId//保存后设置序列的某个组件id
            itemOption.id = compItem.id
          }
        })
      }
    } else {
      // 标注征象字典数据变更
      if (dictionaryData.imageSeriesDataList) {
        let temp = dictionaryData.imageSeriesDataList[LeftHooks.leftHooksData.currentIndex];
        temp && params.acrList.map(item => {//支持多个，但一般都是一个
          const compItem:any = temp.find((it) => (it.id === itemOption.id) && (it.name === itemOption.name))
          if (compItem) {
            item.result = rightHooksData.form[compItem.code];
            compItem.result = rightHooksData.form[compItem.code];
            itemOption.result = rightHooksData.form[compItem.code];
            //
            const current = acrList.find(it => it.componentId === item.componentId)
            compItem.id = current && current.acrId//保存后设置某个病灶的某个组件id
            itemOption.id = compItem.id
          }
        })
      }
    }
  }

  /**
   * 征象表单数据变更方法
   * @param type 当前变更的征象组件类型
   * @returns 返回数组或者字符串形式
   */
  const changeForm = (result: string | null, type: string) => {
    // 1.对于初始空表单的数据调整
    // 结果有值的时候取反直接返回null
    if (!result) return null;
    // 结果有值的时候并且后面的类型为复选框或者二级下拉的时候返回一个空数组
    if (!result && (type === 'checkbox' || type === 'child_select')) return [];
    // 2. 对于有值的时候对表单数据调整
    // 类型为复选框时并且存在逗号的时候通过逗号进行分割
    if (type === "checkbox" && !Array.isArray(result)) return result.split(',');
    // 类型为二级下拉时并且存在@#@符号的时候，通过@#@进行分割
    if (type === "child_select" && !Array.isArray(result)) return result.split('@#@');
    // 排除以上所有情况的其他类型直接返回
    return result;
  }

  /**
   * 切换序列征象，标注征象显示事件
   * @param lesionId 病灶id
   */
  const seriesChangeActive = (lesionId?: number) => {
    rightHooksData.form = {};
    if (LeftHooks.leftHooksData.currentIndex === "") {
      if (FilmRead.dictionaryData.seriesDataList) {
        if (Object.values(FilmRead.dictionaryData.seriesDataList).length !== 0) {
          const options = FilmRead.dictionaryData.seriesDataList[FilmRead.interfaceData?.seriesList[FilmRead.currentThumbnailIndex].seriesUid];
          const tempArr = Object.values(options).map(item => {
            rightHooksData.form[item.code] = changeForm(item.result, item.type);
            return _.cloneDeep({
              ...item,
              title: item.name,
              field: item.code,
              type: item.type
            })
          })
          // @ts-ignore
          rightHooksData.formOptions = tempArr;
        } else {
          // @ts-ignore
          rightHooksData.formOptions = [];
        }
      }
    } else {
      if (FilmRead.dictionaryData.imageSeriesDataList && lesionId) {
        LeftHooks.leftHooksData.currentIndex = lesionId.toString();
        const options = FilmRead.dictionaryData.imageSeriesDataList[lesionId];
        const tempArr = Object.values(options).map(item => {
          rightHooksData.form[item.code] = changeForm(item.result, item.type);
          return _.cloneDeep({
            ...item,
            title: item.name,
            field: item.code,
            type: item.type
          })
        })
        // @ts-ignore
        rightHooksData.formOptions = tempArr;
      }
    }
  }

  /**
   * 针对征象数据增加的方法
   * @param createObj 当前新增的数据集合
   */
  const seriesDataAdd = (...createObj: any[]) => {
    const [list, id] = createObj;
    dictionaryData.imageSeriesDataList && (dictionaryData.imageSeriesDataList[id] = list);
  }

  /**
   * 删除标注征象数据方法
   * @param lesionId 病灶id
   * @param frameId 帧段id
   */
  const seriesDataDel = (lesionId: number) => {
    dictionaryData.imageSeriesDataList && delete dictionaryData.imageSeriesDataList[lesionId];
    // if (dictionaryData.imageDataList) {
    //   if (interfaceData.pageSettingList.imageLayout === 'VIDEO_ANNO' && frameId) {
    //     if (Array.isArray(dictionaryData.imageDataList)) {
    //       dictionaryData.imageDataList[frameId] = dictionaryData.imageDataList.filter(item => item.id != lesionId);
    //     }
    //   } else {
    //     // 删除选中病灶和删除未选中病灶逻辑
    //     delete dictionaryData.imageDataList[lesionId];
    //   }
    // }
  }

  /**
   * 根据当前帧段删除标注征象数据
   * @param frameId 帧段ID
   */
  const seriesFrameDel = (frameId: number) => {
    let lesionIds: number[] = []
    // 获取当前帧段id下的所有病灶id
    dictionaryData.lesionDataList && Array.isArray(dictionaryData.lesionDataList[frameId]) && (lesionIds = dictionaryData.lesionDataList[frameId].map(item => item.id))
    // 删除存在的id数据
    lesionIds.length !== 0 && lesionIds.map(item => {
      dictionaryData.imageSeriesDataList && delete dictionaryData.imageSeriesDataList[item]
    })
  }

  /**
   * 初始根据路由页面类型判定框架右侧组件部分的废片原因阴阳性是否需要展示
   */
  const getCompStatus = () => {
    const pageType = route.query.type as unknown as string;
    if (pageType === "query") {
      // 诊断所得
      rightHooksData.diagnosisVisible = interfaceData.pageSettingList.diagnosis;
      rightHooksData.diagnosisValue = "";
      // 检查所见
      interfaceData.pageSettingList.findings && (rightHooksData.findingVisible = interfaceData.pageSettingList.findings);
      // 是否废片：status标注状态 0-未开始 1-进行中 2-已提交 3-提交废片
      rightHooksData.rejectFilmVisible = interfaceData.resultDataList.status === 3;
      const discardCodeData = getDisCardCodeVal();
      const discardCodeMap = {} as {[x: string]: string};
      interfaceData.discardList && interfaceData.discardList.map(item => {
        discardCodeMap[item.value] = item.name;
      });
      let tempArr = discardCodeData.map(item => discardCodeMap[item]);
      rightHooksData.rejectFilmValue = `${tempArr.join(",")}${interfaceData.resultDataList.discardRemark ? "," + interfaceData.resultDataList.discardRemark : interfaceData.resultDataList.discardRemark}`;
      // 阴阳性
      rightHooksData.yayVisible = interfaceData.resultDataList.yay !== null;
      interfaceData.resultDataList.yay && (rightHooksData.yayValue = interfaceData.resultDataList.yay);
    }
  }

  const getDisCardCodeVal = () => {
    if (interfaceData.resultDataList.discardCode) {
      if (interfaceData.resultDataList.discardCode.includes(",")) {
        return interfaceData.resultDataList.discardCode.split(",");
      } else {
        return [interfaceData.resultDataList.discardCode];
      }
    } else {
      return [];
    }
  }

  const resetHookData = () => {
    rightHooksData.findingVisible = false;
    rightHooksData.findingValue = "";
    rightHooksData.diagnosisVisible = false;
    rightHooksData.diagnosisValue = "";
    rightHooksData.rejectFilmVisible = false;
    rightHooksData.rejectFilmValue = "";
    rightHooksData.yayVisible = false;
    rightHooksData.yayValue = undefined as unknown as number;
    rightHooksData.form = {} as {[x: string | number]: any};
    rightHooksData.formOptions = [] as Right.FormOptions[];
  }

  // 初始化设定为序列征象
  onMounted(() => [seriesChangeActive(), getCompStatus()])

  return {
    rightHooksData,
    handleChange,
    seriesDataAdd,
    seriesChangeActive,
    seriesDataDel,
    resetHookData,
    seriesFrameDel
  }
};

export default useRight;